package com.neusoft.resturant.controller;

import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.exception.BizException;
import com.neusoft.resturant.common.utils.R;
import com.neusoft.resturant.common.utils.SecurityUtils;
import com.neusoft.resturant.entity.LoginUserVo;
import com.neusoft.resturant.entity.SysUser;
import com.neusoft.resturant.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @program: resturant
 * @description:
 * @author: lydms
 * @create: 2023-11-22 15:44
 **/

/**
 * @author: Daniel
 * @date: 2023-10-26 08:41
 **/
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private RedisTemplate redisTemplate;


    @PostMapping("/login")
    public R login(@RequestBody LoginUserVo UserVo) {
        // 1.根据用户名去查询
        SysUser sysUser = sysUserService.selectUserByUserName(UserVo.getUsername());
        if (sysUser == null) {
            throw new BizException(404, "用户不存在");
//            return R.error(404, "用户不存在");

        }
        // 2.存在，判断密码对不对
        boolean ok = SecurityUtils.matchesPassword(UserVo.getPassword(), sysUser.getPassword());
        if (ok) {
            String token = UUID.randomUUID().toString().replace("-", "");
            System.out.println(token);
            redisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 1, TimeUnit.HOURS);
            return R.success("成功登录").put("token", token);
        } else {
            return R.error("密码错误");
        }

    }
    @GetMapping("/get")
    public R getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        String json = (String) redisTemplate.opsForValue().get(token);
        if (json == null) {
            return R.error("redis没有该用户信息");
        }
        SysUser sysUser = JSON.parseObject(json, SysUser.class);

        return R.success(sysUser);
    }

    @GetMapping("/info")
    public R getInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        System.out.println("当前用户id：" + userId);
        return R.success();
    }

}




